<template>
  <div class="tabsCom">
    <el-tabs v-model="editableTabsValue"
             type="card"
             @tab-remove="removeTab"
             @tab-click="tabClick($event)">
      <el-tab-pane v-for="item in editableTabs"
                   :key="item.route"
                   :label="item.title"
                   :name="item.route"
                   :closable="item.flag">
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script>
export default {
  name: 'TabCom',
  computed: {
    // 监听vuex保存的数据
    editableTabs: {
      get () {
        return this.$store.state.tabsPage
      },
      set (val) {
        this.$store.state.tabsPage = val
      }
    },
    editableTabsValue: {
      get () {
        return this.$store.state.TabsValue
      },
      set (val) {
        this.$store.state.TabsValue = val
      }
    }
  },
  methods: {
    removeTab (targetName) {
      let tabs = this.editableTabs
      let activeName = this.editableTabsValue
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.route === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]
            console.log(nextTab)
            if (nextTab) {
              activeName = nextTab.route
            }
          }
        })
      }
      this.editableTabsValue = activeName
      this.editableTabs = tabs.filter(tab => tab.route !== targetName)
      this.$router.push({ name: activeName })
    },
    // 写一个点击tabs跳转
    tabClick (event) {
      this.$router.push({ name: event.name })
    }
  }
}
</script>

<style lang="stylus" scoped></style>
